import axios from "axios";
let baseUrl;
if (process.env.NODE_ENV === "development") {
  // 开发环境
  baseUrl = "http://192.168.1.24:48801/api";
  // baseUrl = "http://192.168.100.81:48801/api";
} else {
  // 生产环境
  // baseUrl = "http://192.168.100.81:48801/api";
  baseUrl = "https://192.168.100.81:48800/api";
}

const service = axios.create({
  baseURL: baseUrl,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 50, // request timeout
});
service.interceptors.request.use(
  (config) => {
    const token = uni.getStorageSync("token");
    if (token) {
      config.headers["Dobo-Auth"] = "bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
service.interceptors.response.use(
  (response) => {
    if (response.data && response.data.code == 200) {
      return response.data;
    } else if ([401, 403, 10010].includes(response.data.code)) {
      uni.clearStorageSync();
      uni.navigateTo({
        url: "/pages/login/index",
      });
    } else {
      uni.showToast({
        icon: "none",
        title: response.data.msg || "服务器错误，请联系管理员！",
        duration: 2000,
      });
      return Promise.reject();
    }
  },
  (error) => {
    if (err.errMsg === "request:fail") {
      uni.showToast({
        icon: "none",
        title: "服务器出错！",
        duration: 2000,
      });
    }
    return Promise.reject(error);
  }
);
export default service;
